<script lang="ts" setup>
import { reactive, onMounted, ref } from 'vue'
import { queryUserInfoTableCol, queryUserInfoRequestData } from '@/api/user/types/user'
import { cancelIdCardVerify, queryUserInfo, userFrozenUnfreeze } from '@/api/user'
import { findStoreByName } from '@/api/store'
import { useTable } from '@/hooks/useTable'
import { getToken } from '@/utils/cache/cookies'
import dayjs from 'dayjs'
import { ElMessage, ElMessageBox, FormInstance } from 'element-plus'
import { useRouter } from 'vue-router'
import { findStoreByNameResponseData } from '@/api/store/types/store'
import { formatGender } from '@/utils/formatter'
defineOptions({
  name: 'UserList'
})
const form = reactive<queryUserInfoRequestData>({
  name: '',
  phone: '',
  storeId: '',
  status: ''
})
const storeList = ref<findStoreByNameResponseData>([])
const formRef = ref<FormInstance | null>(null)
const { pagination, data, loading, handleSizeChange, handleCurrentChange, setCurrentPage, load } =
  useTable<queryUserInfoTableCol>(queryUserInfo, getToken() ?? '', () => form)

const handleFormSearch = () => {
  setCurrentPage(1)
  load()
}

onMounted(() => {
  getStore()
  load()
})
const router = useRouter()

const getStore = () => {
  findStoreByName({
    token: getToken() ?? '',
    storeName: ''
  }).then((res) => {
    if (res.statusCode === '0') {
      storeList.value = res.data
    }
  })
}
const showMoreInfo = (row: queryUserInfoTableCol, type?: 'charge' | 'refund') => {
  router.push({
    name: 'UserInfo',
    query: {
      userId: row.userId,
      phone: row.mobilePhone,
      selectType: type || 'charge'
    }
  })
}
const freeUser = (row: queryUserInfoTableCol) => {
  userFrozenUnfreeze({
    token: getToken() ?? '',
    phone: row.mobilePhone,
    status: '1'
  }).then((res) => {
    if (res.statusCode === '0') {
      ElMessage.success(res.data)
      load()
    }
  })
}
const reset = () => {
  formRef.value?.resetFields()
}

const resetIdCard = (row: queryUserInfoTableCol) => {
  ElMessageBox.confirm(
    '实名注销后，用户将无法正常使用，需要用户重新进行实名认证才可继续使用，是否对其进行销注。',
    '实名注销',
    {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    }
  ).then(() => {
    handleResetCard(row.userId)
  })
}
const handleResetCard = async (id: number) => {
  try {
    const res = await cancelIdCardVerify({
      token: getToken() ?? '',
      userId: id
    })
    if (res.statusCode === '0') {
      ElMessage.success(res.data)
      load()
    }
  } catch (error) {
    console.error(error)
  }
}
</script>

<template>
  <div class="xy-container">
    <el-form :model="form" inline ref="formRef">
      <el-form-item prop="phone" label="手机号">
        <el-input v-model="form.phone" placeholder="请输入" />
      </el-form-item>
      <el-form-item prop="name" label="用户姓名">
        <el-input v-model="form.name" placeholder="请输入" />
      </el-form-item>
      <el-form-item prop="status" label="账户状态">
        <el-select v-model="form.status" placeholder="请选择账户状态" style="width: 150px">
          <el-option value="1" label="正常" />
          <el-option value="0" label="冻结" />
          <el-option value="2" label="实名注销" />
        </el-select>
      </el-form-item>
      <el-form-item prop="storeId" label="所属门店">
        <el-select v-model="form.storeId" placeholder="请选择所属门店" style="width: 150px">
          <el-option
            v-for="item in storeList"
            :key="item.storeId"
            :value="item.storeId"
            :label="item.storeName"
          />
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="handleFormSearch">查询</el-button>
        <el-button @click="reset" plain>重置</el-button>
      </el-form-item>
    </el-form>
    <el-table :data="data" v-loading="loading">
      <el-table-column
        prop="mobilePhone"
        label="手机号"
        show-overflow-tooltip
        align="center"
        min-width="120px"
      />
      <el-table-column prop="userName" label="姓名" align="center" min-width="120px" />
      <el-table-column
        prop="gender"
        label="性别"
        align="center"
        width="80px"
        :formatter="formatGender"
      />
      <el-table-column prop="margin" label="出区域保证金" align="center" min-width="120px" />
      <el-table-column prop="balance" label="短租余额" align="center" min-width="120px" />
      <el-table-column prop="idCard" label="身份证" min-width="200">
        <template #default="scope">
          <span v-if="scope.row.idCard">{{
            scope.row.idCard.replace(scope.row.idCard.substring(6, 14), '********')
          }}</span>
        </template>
      </el-table-column>
      <el-table-column prop="createdTime" label="注册时间" min-width="200">
        <template #default="scope">
          <span>{{ dayjs(scope.row.createdTime).format('YYYY-MM-DD HH:mm:ss') }}</span>
        </template>
      </el-table-column>
      <el-table-column
        prop="storeName"
        label="所属门店"
        align="center"
        width="150px"
        show-overflow-tooltip
      />
      <el-table-column prop="status" label="账号状态" align="center" min-width="120px">
        <template #default="scope">
          <span v-if="scope.row.status == '0'" style="color: var(--xy-danger-color)">冻结</span>
          <span v-else-if="scope.row.status == '1'" style="color: var(--xy-success-color)"
            >正常</span
          >
          <span v-else style="color: var(--xy-success-color)">实名注销</span>
        </template>
      </el-table-column>
      <el-table-column label="充值订单" align="center">
        <template #default="scope">
          <el-button type="primary" class="is-show" link @click="showMoreInfo(scope.row, 'charge')"
            >查看</el-button
          >
        </template>
      </el-table-column>
      <el-table-column label="退款记录" align="center">
        <template #default="scope">
          <el-button type="primary" class="is-show" link @click="showMoreInfo(scope.row, 'refund')"
            >查看</el-button
          >
        </template>
      </el-table-column>
      <el-table-column label="更多信息" align="center">
        <template #default="scope">
          <el-button type="primary" class="is-show" link @click="showMoreInfo(scope.row)"
            >查看</el-button
          >
        </template>
      </el-table-column>
      <el-table-column label="操作" fixed="right" min-width="200px">
        <template #default="scope">
          <el-button
            :disabled="scope.row.status == '1'"
            type="primary"
            link
            @click="freeUser(scope.row)"
            >解除冻结</el-button
          >
          <el-button v-if="scope.row.idCard" type="primary" link @click="resetIdCard(scope.row)"
            >实名注销</el-button
          >
        </template>
      </el-table-column>
    </el-table>
    <div flex justify-end mt-20>
      <el-pagination
        @current-change="handleCurrentChange"
        @size-change="handleSizeChange"
        v-model:current-page="pagination.pageNum"
        v-model:page-size="pagination.pageSize"
        background
        :total="pagination.total"
        layout="total,prev,pager,next,jumper,sizes"
      />
    </div>
  </div>
</template>

<style scoped></style>
